package com.example.ktapplication.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.example.ktapplication.AppGlobals
import com.example.ktapplication.R
import com.example.ktapplication.dialog.DialogLoading
import com.example.ktapplication.model.LoginViewModel
import com.example.ktapplication.state.LoginState
import com.example.ktapplication.utils.event.Event
import com.example.ktapplication.utils.event.EventBusUtil
import com.example.ktapplication.view.CustomTitleBar
import com.google.android.material.textfield.TextInputEditText

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class LoginActivity :AppCompatActivity(){

    private lateinit var titleBar: CustomTitleBar
    private lateinit var imgFind: ImageView
    private lateinit var imgMenu: ImageView
    private lateinit var txtTitle: TextView
    private lateinit var btnLogin: TextView
    private lateinit var registerTip: TextView
    private lateinit var userName: TextInputEditText
    private lateinit var userPwd: TextInputEditText

    private lateinit var login: LoginViewModel
    private var stateJob: Job? = null
    private var showDialog:Boolean = false
    private lateinit var mDialogLoading: DialogLoading



    companion object {
        fun start(context: Context) {
            val intent = Intent(context, LoginActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        mDialogLoading =DialogLoading.instance
        login = ViewModelProvider(this)[LoginViewModel::class.java]
        ///初始化组件
        initView()
    }

    fun initView(){
        titleBar=findViewById<CustomTitleBar>(R.id.titleBar)
        imgFind=titleBar.findViewById<ImageView>(R.id.img_find)
        imgFind.visibility=View.INVISIBLE
        imgMenu=titleBar.findViewById<ImageView>(R.id.img_menu)
        Glide.with(AppGlobals.getApplication()).load(R.mipmap.left).into(imgMenu)
        txtTitle=titleBar.findViewById<TextView>(R.id.txt_title)
        txtTitle.text="登录"

        btnLogin=findViewById<TextView>(R.id.btnLogin)
        registerTip=findViewById<TextView>(R.id.txtRegistTip)
        userName=findViewById<TextInputEditText>(R.id.etName)
        userPwd=findViewById<TextInputEditText>(R.id.etPwd)

        initEvent()
    }

    fun initEvent(){
        imgMenu.setOnClickListener(View.OnClickListener {
            finish()
        })
        registerTip.setOnClickListener(View.OnClickListener {
            val intent =  Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        })
        btnLogin.setOnClickListener(View.OnClickListener {
            var name="";
            name= userName.text.toString();
            var pwd="";
             pwd=userPwd.text.toString();
            if (name.isEmpty()|| pwd.isEmpty()){
                showToast("用户名或者密码不能为空")
            }else{
                showDialog()
                login.login(name,pwd)
            }
        })
        stateJob=lifecycleScope.launch(Dispatchers.IO) {
            ///IO线程
            login.state.collect{ state ->
                dismissDialog()
                when(state){
                    is LoginState.OnSuccess -> {
                        if (state.login!=null){
                            if(state.login!!.errorCode==0){
                                EventBusUtil.eventBus.post(Event.LoginSuc())
                                withContext(Dispatchers.Main){
                                    ///Main线程
                                    finish()
                                }
                            }else{
                                showToast(state.login!!.errorMsg)
                            }
                            state.login!!.count+=1
                        }
                        dismissDialog()
                    }
                    is LoginState.OnError -> {
                        dismissDialog()
                        val error = state.exception!!.message;
                        showToast(error.toString())
                    }
                }
            }
        }
    }

    fun showDialog(){
        showDialog=true
        lifecycleScope.launch(Dispatchers.Main){
            mDialogLoading.setTip("账号登录中...")
            mDialogLoading.show(supportFragmentManager,"login")
        }
    }

    fun dismissDialog(){
        if (showDialog){
            lifecycleScope.launch(Dispatchers.Main){
                mDialogLoading.dismiss()
            }
        }
    }

    fun showToast(msg:String){
        lifecycleScope.launch(Dispatchers.Main){
            Toast.makeText(this@LoginActivity,
                msg,Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        stateJob!!.cancel()
        super.onDestroy()
    }
}